package com.devin.controller;

import com.devin.model.dto.CreateBilibiliDto;
import com.devin.model.dto.JsonResult;
import com.devin.model.dto.RoomDto;
import com.devin.model.entity.BiliVideo;
import com.devin.model.entity.Movie;
import com.devin.model.entity.Room;
import com.devin.service.BilibiliService;
import com.devin.service.MovieService;
import com.devin.service.RoomService;
import com.devin.util.BilibiliUtil;
import com.devin.util.RedisUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 *  
 *  @author devin
 *  @date 2020-04-14 11:17
 *  @version 1.0.2
*/

@ResponseBody
@Slf4j
@Controller
public class RoomApi {

    private final BilibiliService bilibiliService;

    private final MovieService movieService;

    private final RedisUtil redisUtil;

    private final RoomService roomService;

    @Autowired
    public RoomApi(BilibiliService bilibiliService, RedisUtil redisUtil, RoomService roomService, MovieService movieService) {
        this.bilibiliService = bilibiliService;
        this.redisUtil = redisUtil;
        this.roomService = roomService;
        this.movieService = movieService;
    }

    @RequestMapping("/getRoomById")
    public JsonResult getRoomById(Long roomId){
        log.info("获得房间信息+" + roomId);
        Optional<Room> room = roomService.fetchById(roomId);
        if(!room.isPresent()){
            return new JsonResult(0,"没用找到该房间");
        }else{
            return new JsonResult(1,"获取房间信息成功",room.get());
        }
    }

    /*
    * 根据视频链接去查询是否存在
    * */

    @RequestMapping("/createBilibili")
    public JsonResult createBilibili(CreateBilibiliDto bilibiliDto) throws IOException {
        log.info(bilibiliDto.toString());
        HashMap<String,Object> hashMap = new HashMap<String,Object>();
        BiliVideo video = null;
        video = bilibiliService.findByLink(bilibiliDto.getLink());
        if(video == null){
            video = BilibiliUtil.getVideo(bilibiliDto.getLink()).get();
            video = bilibiliService.create(video);
        }
        if(video == null){
            return new JsonResult(0,"创建房间失败");
        }else{
            Room room = Room.builder()
                    .roomname(bilibiliDto.getRoomname())
                    .videoname(video.getTitle())
                    .movieId(video.getId())
                    .createTime(new Date())
                    .hostname(bilibiliDto.getHostname())
                    .currentPeople(1)
                    .face(video.getFace())
                    .kind("bilibili").build();
            Room returnRoom = roomService.create(room);

            List<String> userlist = new ArrayList<>(1);
            userlist.add(bilibiliDto.getHostname());
            boolean set = redisUtil.set(returnRoom.getId().toString(), userlist);
            if(!set){
                return new JsonResult(0,"创建房间失败");
            }else{
                //创建一个房间 返回视频id 和房间id
                hashMap.put("videoId",video.getId());
                hashMap.put("roomId",returnRoom.getId());
                return new JsonResult(1,"创建房间成功",hashMap);
            }

        }
    }




    @ApiOperation(value = "创建房间")
    @RequestMapping("/create")
    public JsonResult   createRoom(RoomDto roomDto, HttpSession session){

        String username = (String) session.getAttribute("username");
        //把房间加入房间列表
        log.info("用户：" + username + "  创建房间");

        //得到房间的电影
        Movie movie = movieService.getById(roomDto.getMovieId());

        //创建房间
        Room room = Room.builder()
                .roomname(roomDto.getRoomname())
                .videoname(roomDto.getVideoname())
                .movieId(movie.getId())
                .createTime(new Date())
                .hostname(username)
                .currentPeople(1)
                .face(movie.getFace())
                .kind("movie").build();

        //把房间放进去
        Room save = roomService.create(room);
        log.info("房间创建成功");
        // redis把房间的人加入房间id
        List<String> userlist = new ArrayList<>(1);
        userlist.add(username);
        boolean rediscode = redisUtil.set(save.getId().toString(), userlist);
        log.info("建用户放入数据库成功");
        //看成功与否返回
        HashMap<String,Object> hashMap = new HashMap<String,Object>();
        if(!rediscode){
            return new JsonResult(0,"创建房间失败");
        }else {
            hashMap.put("roomId",save.getId());
            return new JsonResult(1,"success",hashMap);
        }

    }


    /*
     * 进入房间   1. 把用户名加入对应房间redis   更新房间的人数
     * */
    @RequestMapping("/enterRoom")
    public Room enterRoom(Long roomId, String username){

        log.info(username + " enter roomid " + roomId);
        //得到房间的名字
        Room room = roomService.getById(roomId);
        room.setCurrentPeople(room.getCurrentPeople()+1);
        roomService.create(room);

        List<String> userlist = (List<String>) redisUtil.get(roomId.toString());
        userlist.add(username);
        redisUtil.set(roomId.toString(), userlist);
        return room;
    }

    /*
    *   获得所有的房间
    * */
    @RequestMapping("/roomList")
    public Page<Room> getRoomList(@PageableDefault(size = 8,page = 0,sort = "createTime") Pageable pageable)
    {
        return  roomService.listAll(pageable);
    }
}
